package org.iipg.common.data.autoconfig;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.iipg.common.data.property.FastJsonProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: zhuhy163@163.com Date: 2020/9/21
 */
@Configuration
@EnableConfigurationProperties(FastJsonProperties.class)
@ComponentScan(basePackages = "org.iipg.common.data")
@RequiredArgsConstructor
public class FastJsonConfiguration implements WebMvcConfigurer {

	private final FastJsonProperties fastjsonProperties;

	@Bean
	@Primary
	public HttpMessageConverters httpMessageConverter() {
		FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

		fastJsonHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));

		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames, SerializerFeature.WriteMapNullValue,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.PrettyFormat);
		fastJsonConfig.setDateFormat(fastjsonProperties.getDateFormat());

		List<MediaType> mediaTypeList = new ArrayList<>();
		mediaTypeList.add(MediaType.APPLICATION_JSON);
		fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypeList);
		fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
		return new HttpMessageConverters(new HttpMessageConverter[] { fastJsonHttpMessageConverter });
	}

	// @Override
	// public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
	// for (HttpMessageConverter<?> messageConverter : converters) {
	// System.out.println(messageConverter); // 2
	// }
	// }

}
